package com.cardvalue.sys.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.cardvalue.sys.R;
import com.cardvalue.sys.activity.AddressActivity;
import com.cardvalue.sys.activity.LinkActivity;
import com.cardvalue.sys.activity.LinkAgeThree;
import com.cardvalue.sys.base.BaseFragment;
import com.cardvalue.sys.cache.LocalCache;
import com.cardvalue.sys.entity.Credit;
import com.cardvalue.sys.entity.User;
import com.cardvalue.sys.mode.UserService;
import com.cardvalue.sys.tool.CheckingForm;
import com.cardvalue.sys.tool.DateFormatTool;
import com.cardvalue.sys.tool.MessageBox;
import com.cardvalue.sys.tool.Utiltools;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.fraudmetrix.android.FMAgent;
import io.realm.Realm;
import io.realm.RealmResults;

/**
 *基础额度 （基础资料）
 */
public class BasicFragment extends BaseFragment {
    @Bind(R.id.baselimit_financing) EditText loanAmount;// 期望融资金额
    @Bind(R.id.deadline) TextView planFundTerm; // 期望融资期限
    @Bind(R.id.tv_industryPId) TextView tv_industryPId; // 所属行业
    @Bind(R.id.regist_num) EditText bizRegisterNo; // 营业执照注册号
    @Bind(R.id.baselimit_address) TextView businessAddress;// 营业地址
    @Bind(R.id.store_number) EditText numLocations; // 门店数
    @Bind(R.id.businessName)  EditText businessName;  //经营名称
    @Bind(R.id.tv_proposerName) EditText ownerName;// 申请人
    @Bind(R.id.tv_add_post) TextView addPost;// 添加pos商编
    @Bind(R.id.tv_referenceline) TextView tv_referenceline;//参考额度
    @Bind(R.id.loanPeriod) TextView loanPeriod;//参考融资期限
    @Bind(R.id.paymentMethod)  TextView paymentMethod;//还款方式
    @Bind(R.id.whetheradd) TextView whetheradd;//额度是否满意   gone
    @Bind(R.id.ly_bottom) LinearLayout ly_bottom;//与额度有关的 gone
    @Bind(R.id.lastUpdateTimeday)  TextView lastUpdateTimeday;//以上参考融资方案有效期85天
    @Bind(R.id.invalidDate)  TextView  invalidDate;//至2020-06-17为止。
    @Bind(R.id.basiclimit_submit) Button mSubmit;

    private View view;
    private UserService updateInfo;
    public  static Handler handler;
    private String mbusinessAddress;//地址
    private String mbizAddrLonlat;//地址的经纬度
    private  String mplanFundTerm;//融资期限几个月
    private  String   planFundTermName;//融资期限的名字
    private  Realm realm;
    String mIndustryGId;
    String mIndustryPId;
    String mIndustryCId;
    private static int numTime = 120;
    private Timer timer;
    private TimerTask timerTask;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view=inflater.inflate(R.layout.fragment_basic,null);
        ButterKnife.bind(this,view);
        realm = Realm.getDefaultInstance();
        dialog=new ProgressDialog(getActivity(),R.style.dialog);
        updateInfo=new UserService(getActivity());
        numLocations.setText(numLocations.getText().toString());
        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if(msg.what==1){//选择地址
                    Bundle bundle = msg.getData();
                    mbusinessAddress=bundle.get("businessAddress").toString().trim();
                    mbizAddrLonlat=bundle.get("lngAndlat").toString().trim();
                    businessAddress.setText(mbusinessAddress);
                }else if(msg.what==0x1000){//融资期限
                    Bundle bundle = msg.getData();
                    planFundTermName=bundle.get("title").toString().trim();
                    mplanFundTerm=bundle.get("id")+"";
                    planFundTerm.setText(planFundTermName);
                }else if(msg.what==0x1001){//行业的第一级
                    Bundle bundle=msg.getData();
                    mIndustryGId=bundle.get("Gid").toString();
                    mIndustryPId=bundle.get("Pid").toString();
                    mIndustryCId=bundle.get("Cid").toString();
                    tv_industryPId.setText(bundle.get("title").toString());
                }else if(msg.what==0x1005){//每隔5s调用获取授信
                    Credit(LocalCache.getStringLocalData(getActivity(),"creditId"));
                }
            }
        };
        setData();
        return view;
    }

    /**
     * 选择经营地址
     */
    @OnClick(R.id.baselimit_address) void clickBusinessAddress(){
        Intent intent=new Intent(getActivity(),AddressActivity.class);
        if(businessAddress.getText().toString().trim().equals("")){
            intent.putExtra("text","");
            startActivity(intent);
            return;
        }else{
            intent.putExtra("text",businessAddress.getText().toString().trim());
            startActivity(intent);
        }
    }

    //所属行业
    @OnClick(R.id.tv_industryPId) void clickIndustry(){
        Intent intent=new Intent(getActivity(), LinkAgeThree.class);//LinkAgeThree    LinkActivity
        intent.putExtra("tagName","Industry");
        startActivity(intent);
    }
    /**
     * 融资期限
     */
    @OnClick(R.id.deadline) void clickDeadline(){
        Intent intent=new Intent(getActivity(),LinkActivity.class);
        intent.putExtra("tagName","PlanFundTerm");
        startActivity(intent);
    }

    /**
     * 提交按钮
     */
    @OnClick(R.id.basiclimit_submit) void clickSubmit(){
        String mloanAmount=loanAmount.getText().toString();
        String mbizRegisterNo=bizRegisterNo.getText().toString();
        String mnumLocations=numLocations.getText().toString();
        String mbusinessName=businessName.getText().toString();
        String mownerName=ownerName.getText().toString();
        String mbusinessAddress=businessAddress.getText().toString();
        if(!CheckingForm.checkForBasic(mloanAmount,mplanFundTerm,mIndustryGId,mIndustryPId,
                mIndustryCId,mbizRegisterNo,mbusinessAddress,mnumLocations,mbusinessName,
                mownerName)){
            MessageBox.ToastShow(CheckingForm.LastError,getActivity());
            return;
        }
        MessageBox.show(dialog,"","提交中");
        User user=new User();
        user.setBizRegisterNo(mbizRegisterNo);//营业注册号
        user.setIndustryGId(mIndustryGId);//所属行业(一级)
        user.setIndustryPId(mIndustryPId);//所属行业(二级)
        user.setIndustryCId(mIndustryCId);//所属行业(三级)
        user.setLoanAmount(mloanAmount);//拟融资金额
        user.setBusinessName(mbusinessName);//企业经营名称
        user.setBizAddrLonlat(mbizAddrLonlat);//经纬度
        user.setBusinessAddress(mbusinessAddress);//营业地址
        user.setPlanFundTerm(mplanFundTerm);//拟融资期限月数
        user.setNumLocations(mnumLocations);//门店数TextUtils.isEmpty(numLocations.getText().toString())
        user.setOwnerName(mownerName);//申请人
        String blackBox = FMAgent.onEvent();
        user.setBlackBox(blackBox);//同盾
        updateInfo.updateInfo(user, new UserService.UsesrCallback() {//更新用户
            @Override
            public void success(User userInfo) {//成功，更新用户
                dialog.cancel();
                updateInfo.getGetUserInfo(LocalCache.getStringLocalData(getActivity(), "objectId"), new UserService.UsesrCallback() {//获取用户
                    @Override
                    public void success(User userInfo) {//更新用户成功，创建授信，获取授信     之后调用倒计时
                        setData();
                        //if(TextUtils.isEmpty(LocalCache.getStringLocalData(getActivity(),"creditId"))){//creditId登录空，说明要授信
                        Utiltools.printE("creditId登录空，说明要授信","====creditId登录空，说明要授信");
                        updateInfo.getCreditLimit(new UserService.CreditLimitCallback() {//创建授信
                            @Override
                            public void success(Credit creditLimit) {
                                String creditId=creditLimit.getObjectId()+"";
                                if(creditId.equals("null")){
                                    MessageBox.show(dialog,"",creditLimit.getError()+"");
                                    return;
                                }
                                //createNewCredit(creditId);
                                Credit(creditId);
                                startCount();
                            }

                            @Override
                            public void fail(String msg) {

                            }

                            @Override
                            public void cancelDialog() {

                            }
                        });
                      /*  }else{//
                            createNewCredit(creditId);
                        }*/

                    }

                    @Override
                    public void fail(String msg) {

                    }

                    @Override
                    public void cancelDialog() {

                    }
                });
            }

            @Override
            public void fail(String msg) {

            }

            @Override
            public void cancelDialog() {
                dialog.cancel();
            }
        });
    }



    /**
     * 设置文本框的数据
     */
    public  void  setData(){
        RealmResults<User> results2 = realm.where(User.class).findAll();
        User results1 =realm.where(User.class).equalTo("mobilePhone",LocalCache.getStringLocalData(getActivity(),"mobilePhone")).findFirst();
        if(TextUtils.isEmpty(results2.size()+"")){
            return;
        }
        loanAmount.setText(results1.getLoanAmount());
        planFundTerm.setText(results1.getPlanFundTermName());
        if(!TextUtils.isEmpty(results1.getIndustryGName())){
            tv_industryPId.setText(results1.getIndustryGName()+","+results1.getIndustryPName()+","+results1.getIndustryCName());
        }
        bizRegisterNo.setText(results1.getBizRegisterNo());
        businessAddress.setText(results1.getBusinessAddress());
        numLocations.setText(results1.getNumLocations());
        businessName.setText(results1.getBusinessName());
        ownerName.setText(results1.getOwnerName());

        mplanFundTerm=results1.getPlanFundTerm();
        mIndustryGId=results1.getIndustryGId();
        mIndustryPId=results1.getIndustryPId();
        mIndustryCId=results1.getIndustryCId();
        mbizAddrLonlat=results1.getBizAddrLonlat();

        //获取授信
        Utiltools.printE("SETDATATA===","===="+TextUtils.isEmpty(LocalCache.getStringLocalData(getActivity(),"creditId")));
        if(!TextUtils.isEmpty(LocalCache.getStringLocalData(getActivity(),"creditId"))){
            setDataCredit();//如果有授信id的话，可以直接去缓存中取
        }
/*   for(User c:results2) {
            loanAmount.setText(c.getLoanAmount());
            loanAmount.setText(c.getLoanAmount());
            planFundTerm.setText(c.getPlanFundTermName());
            tv_industryPId.setText(c.getIndustryGName()+","+c.getIndustryPName()+","+c.getIndustryCName());
            bizRegisterNo.setText(c.getBizRegisterNo());
            businessAddress.setText(c.getBusinessAddress());
            numLocations.setText(c.getNumLocations());
            businessName.setText(c.getBusinessName());
            ownerName.setText(c.getOwnerName());

            mplanFundTerm=c.getPlanFundTerm();
            mIndustryGId=c.getIndustryGId();
            mIndustryPId=c.getIndustryPId();
            mIndustryCId=c.getIndustryCId();
            mbizAddrLonlat=c.getBizAddrLonlat();
           *//*
            tv_referenceline.setText(c.getBusinessName());
            loanPeriod.setText(c.getbusinessName());
            paymentMethod.setText(c.getbusinessName());*//*
        }*/

    }


    /**
     * 获取授信
     * @param creditId
     */
    public  void  Credit(String creditId){
        Utiltools.printE("获取授信4444444=","获取授信4444444="+creditId+"=====creditId");
        NotEdit();//不可以编辑
        handler.sendEmptyMessageDelayed(0x1005,5000);
        updateInfo.getCreditLimitService(creditId, new UserService.GetCreditCallback() {  //获取授信
            @Override
            public void success(Credit creditLimit) {
                Utiltools.printE("获取授信的状态====",creditLimit.getCreditStatus()+"");
                if(creditLimit.getCreditStatus()==null||creditLimit.getCreditStatus().equals(""))
                    return;
                if(creditLimit.getCreditStatus().equals("N")|| creditLimit.getCreditStatus().equals("E")||numTime<=0){
                    LocalCache.saveDataToLocal(getActivity(),"creditStatus",creditLimit.getCreditStatus());//保存creditStatus到缓存
                    setDataCredit();
                    handler.removeMessages(0x1005);
                    timer.cancel();
                    timerTask.cancel();
                    numTime=120;
                    mSubmit.setText("继续");
                    mSubmit.setEnabled(true);
                    NotEditYes();//可以编辑
                    //获取授信成功之后，到第二个界面
                    HomePageFragment.mViewPager.setCurrentItem(1);
                }
            }

            @Override
            public void fail(String msg) {

            }

            @Override
            public void cancelDialog() {

            }
        });
    }

    /**
     * 设置获取授信成功时，参考额度里面的值
     */
    public void setDataCredit(){
        Credit results1 =realm.where(Credit.class).equalTo("creditStatus",LocalCache.getStringLocalData(getActivity(),"creditStatus")).findFirst();
        Utiltools.printE("设置获取授信成功时，参考额度里面的值","==="+ JSON.toJSONString(results1));
        if (results1 != null) {
            ly_bottom.setVisibility(View.VISIBLE);
            tv_referenceline.setText(results1.getTotalCreditLine()+""); //参考额度amountRequested
            loanPeriod.setText(results1.getLoanPeriod()+"天");//融资期限
            paymentMethod.setText(results1.getPaymentMethod());//还款方式
            int decDate=  DateFormatTool.decDate(results1.getLastUpdateTime(),results1.getInvalidDate());
            if(decDate==0){
                lastUpdateTimeday.setText("您的额度已过期");
                invalidDate.setVisibility(View.GONE);
            }else{
                lastUpdateTimeday.setText("以上参考融资方案有效期"+decDate+"天");
                invalidDate.setText("至"+results1.getInvalidDate()+"为止。");
            }
        }
    }

/**
 * 获取授信返回的数据
 * {
 "applicationId": 0,
 "code": 0,
 "creditStatus": "N",
 "invalidDate": "2016-06-30",
 "lastUpdateTime": "2016-05-10 16:04:05",
 "loaded": true,
 "loanPeriod": 91,
 "paymentMethod": "每周-账户直接扣款",
 "paymentMethodId": "2",
 "totalCreditLine": 27000,
 "valid": true
 }
 */


    /**
     * 倒计时
     */

    private void startCount(){
        Utiltools.printE("倒计时4444444=","倒计时4444444=");
        timer=new Timer();
        timerTask=new TimerTask() {
            @Override
            public void run() {
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        numTime--;
                        if (numTime>0){
                            mSubmit.setEnabled(false);
                            mSubmit.setText(numTime + "s");
                        }else{
                            mSubmit.setEnabled(true);
                            mSubmit.setText("继续");
                            timerTask.cancel();
                            numTime=120;
                        }
                    }
                });
            }
        };

        timer.schedule(timerTask, 0, 1000);
    }

    /**
     * 正在创建申请   获取用户信息  正在获取最新申请
     */
    public void createNewCredit(String creditId){
     final  String credit=creditId;
        // 当isEnable 为0 时表示申请未激活，还未有申请
        if(LocalCache.getStringLocalData(getActivity(),"isEnabled").equals("0")){
            //创建申请
            updateInfo.NewCreditInfo(null);
            //获取用户信息
            updateInfo.getGetUserInfo(LocalCache.getStringLocalData(getActivity(), "objectId"),null);
            //获取最新的申请
            updateInfo.latesApplication(null);
            //获取授信
            Credit(credit);
            startCount();
            //创建申请
        }else{
            //获取授信
            Credit(credit);
            startCount();
        }
    }




    /**
     * 不可以编辑的时候，颜色是灰色，箭头隐藏
     */
    public void NotEdit(){
        loanAmount.setTextColor(this.getResources().getColor(R.color.c8c8ce));
        businessName.setTextColor(this.getResources().getColor(R.color.c8c8ce));
        planFundTerm.setTextColor(this.getResources().getColor(R.color.c8c8ce));
        planFundTerm.setCompoundDrawables(null, null, null, null);
        addPost.setCompoundDrawables(null, null, null, null);
        businessAddress.setCompoundDrawables(null, null, null, null);
        tv_industryPId.setCompoundDrawables(null, null, null, null);
        tv_industryPId.setTextColor(this.getResources().getColor(R.color.c8c8ce));
        bizRegisterNo.setTextColor(this.getResources().getColor(R.color.c8c8ce));
        businessAddress.setTextColor(this.getResources().getColor(R.color.c8c8ce));
        numLocations.setTextColor(this.getResources().getColor(R.color.c8c8ce));
        ownerName.setTextColor(this.getResources().getColor(R.color.c8c8ce));
    }


    /**
     * 可以编辑的时候，箭头出现
     */
    @SuppressWarnings("deprecation")
    public void NotEditYes(){
        loanAmount.setTextColor(this.getResources().getColor(R.color.head_fold));
        businessName.setTextColor(this.getResources().getColor(R.color.head_fold));
        planFundTerm.setTextColor(this.getResources().getColor(R.color.head_fold));
        Drawable drawable = getResources().getDrawable(R.mipmap.ic_right);
        drawable.setBounds(0, 0, 40, 40);
        planFundTerm.setCompoundDrawables(null, null,drawable, null);
        addPost.setCompoundDrawables(null, null,drawable, null);
        businessAddress.setCompoundDrawables(null, null,drawable, null);
        tv_industryPId.setCompoundDrawables(null, null,drawable, null);
        tv_industryPId.setTextColor(this.getResources().getColor(R.color.head_fold));
        bizRegisterNo.setTextColor(this.getResources().getColor(R.color.head_fold));
        businessAddress.setTextColor(this.getResources().getColor(R.color.head_fold));
        numLocations.setTextColor(this.getResources().getColor(R.color.head_fold));
        ownerName.setTextColor(this.getResources().getColor(R.color.head_fold));
    }

}

